package com.yonyougov.devops.cruxcisupport.server.serversynuser;

import com.yonyougov.devops.cruxcisupport.server.ServerEntity;
import com.yonyougov.devops.cruxcisupport.server.ServerService;
import com.yonyougov.devops.cruxcisupport.userserver.UserServerService;
import com.yonyougov.devops.cruxcisupport.util.SshUtil;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 当在服务器上添加了用户的公钥的时候，用户自动关联这台服务器，如果没有用户的公钥，就取消关联
 */
@Component
@RestController
public class ServerSynUser {

    @Autowired
    private ServerService serverService;
    @Autowired
    private UserServerService userServerService;

    //@PostConstruct
    @GetMapping("test")
    public void syn(){
        // 搜索服务器公钥反查用户
        HashMap<Object, ArrayList> serverMap = new HashMap<>();
        ServerEntity build = ServerEntity.builder().id(BigInteger.valueOf(3366055980095097732L)).build();
        build.setPageAble(false);
        SshUtil sshUtil = new SshUtil();
        serverService.findAllBy(build).getDatas().stream().filter(e->e.getState().equals(1)).forEach(s->{
            if(!serverMap.containsKey(s.getId()))serverMap.put(s.getId(),new ArrayList<>());
            String result = sshUtil.exeCmd(s, "[ -f \"/root/.ssh/authorized_keys\" ] && cat /root/.ssh/authorized_keys || echo \"false\"");
            if(null != result && !"false".equals(result)){
                for (String publicKey : result.split("\n")) {
                    serverMap.get(s.getId()).add(publicKey);
                }
            }
        });
        System.out.println("sdfsdf");
        //Runnable r = () -> serverEntities.forEach(s -> {
        //    userUpdServePublicKey(oldPublicKey,userEntity.getPublicKey(),serverEntities);
        //});
        // 查出数据库
        HashMap<Object, ArrayList> userMap = new HashMap<>();

        //Runnable r = () -> serverEntities.forEach(s -> {
        //    userUpdServePublicKey(oldPublicKey,userEntity.getPublicKey(),serverEntities);
        //});
        // 对比

        // 服务器有的新增入库
    }

}
